<?php
namespace Weixin\Controller;
use Think\Controller;
class IndexController extends Controller{
    private $appid="你的appid";
    private $secret = "你的secret";
    public function index(){
    	//获得nonce,timestamp,echostr,signature
        $nonce = $_GET['nonce'];
        $token = 'ruoshui';
        $timestamp = $_GET['timestamp'];
        $echostr = $_GET['echostr'];
        $signature = $_GET["signature"];
        // 形成数组,然后按照字典排序
        $tmpArr  = array($nonce,$timestamp,$token);
        sort($tmpArr);
        // 拼接成字符串,sha1加密, 然后和signature进行比较
        $tmpstr = implode($tmpArr);
        $tmpstr = sha1($tmpstr);
        if($echostr && $tmpstr == $signature){
        	echo $echostr;
        }else{
        	$this->responseMsg();
        }
    }
    //接受事件推送并回复
    public function responseMsg(){
    	// 1.获取微信推送过来的消息,xml格式
    	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //$postStr = file_get_contents("php://input");
    	// 2.处理消息内容,并设置回复类型和内容
    	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
    	//file_put_contents('./Weixin/Controller/tmp', $this->tpl['text']);
    	switch(strtolower($postObj->MsgType)){
    		case 'event':
    			$this->_doEvent($postObj);
    			break;
    		case 'text':
    			$this->_doText($postObj);
    			break;
    	}
    }
    private function _doEvent($postObj){
        //你要导入的类库文件名的后缀不是class.php而是php，那么可以使用import方法的第三个参数指定后缀：
        //第二个参数作为起始导入路径
    	Vendor("IndexModel",dirname(__FILE__),'.php');//导入自定义类
        $wx = new \IndexModel();
        if($postObj->EventKey=="a1"){
            $content = "你点击的是菜单1";
            $info = $wx->_doText($postObj,$content);
            echo $info;
            exit;
        }
        if($postObj->Event == "subscribe"){
            $content = "欢迎关注若水哥哥的小站。".PHP_EOL."帅哥美女快来和我聊天吧!";
             $info = $wx->_doText($postObj,$content);
    		echo $info;
    	}
        if($postObj->Event == "SCAN"){
            if($postObj->EventKey==188){
                $content = "这是188临时二维码";
            }elseif($postObj->EventKey==666){
                $content = "这是666永久二维码";
            }
            $info = $wx->_doText($postObj,$content);
            echo $info;
        }

    }
    private function _doText($postObj){
        Vendor("IndexModel",dirname(__FILE__),'.php');
        $wx = new \IndexModel();
        switch(strtolower(trim($postObj->Content))){
            case "图文":
                $arr = array(
                array('title'=>'百度',
                      'Description'=>'这是测试描述',
                      'PicUrl'=>'http://news.baidu.com/resource/img/logo_news_276_88.png?date=20150104',
                      'Url'=>'http://www.baidu.com'
                    ),
                array('title'=>'好123',
                      'Description'=>'这是描述2',
                      'PicUrl'=>'https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/r/image/2016-12-02/e4726c987ccad2a1d0e96012838f6c4c.png',
                      'Url'=>'http://www.hao123.com'
                    )
                );
                $res = $wx->_doImage($postObj,$arr);
                echo $res;
            break;
            case 'hello':
                $content = "hello 你好,我是若水";
                $info = $wx->_doText($postObj,$content);
            break;
            case '你好':
                $content = '你好,我是若水哥哥';
                $info = $wx->_doText($postObj,$content);
            break;
            default:
                $content = $this->auto_response($postObj->Content);
                $info = $wx->_doText($postObj,$content);
        }   
        echo $info;	
    	//file_put_contents('./Weixin/Controller/tmp', $Content);
    }
    /*public function http_curl(){
        // 1.初始化curl
        $ch = curl_init();
        $url = "http://www.baidu.com";
        // 2.设置curl参数   
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 3.采集
        $output = curl_exec($ch);
        // 4.关闭
        curl_close($ch);
        print_r($output);exit;
    }*/
    //获取accesstoken
    private function getWxAccesstoken(){
        $file = dirname(__FILE__).'\access_token';
        if(file_exists($file)){   
            $content = file_get_contents($file);
            $content = json_decode($content);//转换成对象
            if(time()-filemtime($file)<$content->expires_in){
                return $content->access_token;
            }
        }
        //设置url
        $appid = $this->appid;
        $secret = $this->secret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;

        //thinkphp自动加载;
        $getcurl = new \Org\Curl\Curl;
        //获取微信返回结果
        $res = $getcurl->getCurl($url);
        file_put_contents($file,$res);
        $content = json_decode($res,true);//转换成数组
        return $content['access_token'];
    }
    //获取微信服务器ip列表
    public function getIp(){
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$this->getWxAccesstoken();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        $res = curl_exec($ch);  
        curl_close($ch);
        $arr = json_decode($res,true);
        var_dump($arr);exit;
    }
    /**
    * 获取ticket(注意权限问题)
    * @param int $scene     场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
    * @param int $expire_seconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
    * @param str $type 二维码类型,tmp为临时,否则为永久
    * @return str $content->ticket 返回票据ticket
    */
    public function getTicket($scene_id=1,$action_name='tmp',$expire_seconds=604800){
            $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->getWxAccesstoken();
        if($action_name){ 
            $arr = '{"expire_seconds": '.$expire_seconds.', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
        }else{
            $arr = '{"action_name": '.QR_LIMIT_SCENE.', "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
        }
            $getCurl = new \Org\Curl\Curl;
            $res = $getCurl->getCurl($url,true,'post',$arr);
            $content = json_decode($res);
        return $content->ticket;

    }
    // 获取临时二维码
    public function getTmpQRCode(){
        $ticket = UrlEncode($this->getTicket(188));
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;
        //获取到ticket可以直接用img标签显示,但是url显示出了ticket.感觉不安全
        //echo "<image src='$url'width='200' height='200'/>";
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url);
        header("Content-type:image/jpeg");
        echo $res;//'<div style="width:200px;height:200px;">'..'</div>';

    }
    //获取永久二维码
    public function getForeverQRCode(){
        $ticket = UrlEncode($this->getTicket(666,'forever'));
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;
        //获取到ticket可以直接用img标签显示,但是url显示出了ticket.感觉不安全
        //echo "<image src='$url'width='200' height='200'/>";
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url);
        header("Content-type:image/jpeg");
        echo $res;//'<div style="width:200px;height:200px;">'..'</div>';

    }
    //发送自定义消息模板
    public function setTmpTemplateMsg(){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->getWxAccesstoken();
         /*
         {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",            
           "data":"first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177"
                   }
            }
        */
        //定义模板内容 
        $arr = array(
            "touser"=>"oEN_iw-oKZNhEwmCAem7Nyvori3M",//给谁发的微信号,相当于Obj->FromUserName,接口号关注列表显示
            "template_id"=>"KDXMg8PjvXxb2ErIfFWyZZoIYFldGnBH0bfbKsPxT6c",//消息模板id
            "url"=>"http://user.qzone.qq.com/963087326/infocenter?ptsig=ZlaFdxNF624ri7tM2X*xrkK0GD-waNbcxgXIXjR0pGg_",//点击模板跳转的地址
            "data"=>array(
                "name"=>array(//自定义模板内变量
                    "value"=>"若水",
                    "color"=>"#173177"
                    ),
                "money"=>array(
                    "value"=>"888元",
                    "color"=>"#173177"
                    ),
                "date"=>array(
                    "value"=>date("Y-m-d H:i:s"),
                    "color"=>"#173177"
                    ),
                "tip"=>array(
                    "value"=>"欢迎下次光临",
                    "color"=>"#173177"
                    )
                )
            );
        //将数据转换成json格式
        $data = json_encode($arr);
        //实例化curl类
        $getCurl = new \Org\Curl\Curl;
        //以post方式提交
        $res = $getCurl->getCurl($url,true,'post',$data);
        var_dump($res);exit;
    }
    //群发功能
    public function sedMsgAll(){
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$this->getWxAccesstoken();
        /*{     
            "touser":"OPENID",
            "text":{           
                   "content":"CONTENT"            
                   },     
            "msgtype":"text"
        }*/
        //发送单文本
        $arr = array(
            "touser"=>"oEN_iw-oKZNhEwmCAem7Nyvori3M",
            "text"=>array(
                "content"=>urlencode("测试:this is very good")
                ),
            "msgtype"=>"text"
            );
        //发送单图文(达到每次限额次数,没有测试成功)
        /*{
           "touser":"OPENID", 
           "mpnews":{              
                    "media_id":"123dsdajkasd231jhksad"               
                     },
           "msgtype":"mpnews" 
        }*/
        /*$arr = array(
            "touser"=>"oEN_iw-oKZNhEwmCAem7Nyvori3M",
            "mpnews"=>array(
                "media_id"=>"123dsdajkasd231jhksad"
                ),
            "msgtype"=>"mpnews"
            );*/
        //不使用urlencode加密和urldecode解密会乱码
        $data = urldecode(json_encode($arr));
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url,true,'post',$data);
        var_dump($res);exit;
    }
    public function setMenu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->getWxAccesstoken();
        $arr = array(
            "button"=>array(
                    array(
                            "type"=>"click",
                            "name"=>urlencode("菜单一"),
                            "key"=>"a1"
                        ),
                    array(
                        "name"=>urlencode("菜单二"),
                        "sub_button"=>array(
                                array("type"=>"view",
                                    "name"=>urlencode("菜单1"),
                                    "url"=>"http://www.baidu.com"
                                    ),
                                array("type"=>"view",
                                    "name"=>urlencode("菜单2"),
                                    "url"=>"http://www.baidu.com"
                                    ),
                                array("type"=>"view",
                                    "name"=>urlencode("菜单2"),
                                    "url"=>"http://www.baidu.com"
                                    )
                            )
                        ),
                    array(
                            "type"=>"view",
                            "name"=>urlencode("菜单三"),
                            "url"=>"http://www.baidu.com"
                        )
                    )
            );
        $data = urldecode(json_encode($arr,true));
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url,true,'post',$data);
        var_dump($res);exit;
    }
    //获取用户的openid
    //网址:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html#.E7.AC.AC.E4.B8.80.E6.AD.A5.EF.BC.9A.E7.94.A8.E6.88.B7.E5.90.8C.E6.84.8F.E6.8E.88.E6.9D.83.EF.BC.8C.E8.8E.B7.E5.8F.96code
    //https://qq963087326.myue.xzbiz.cn/index.php/Weixin/index/getBaseInfo生成二维码
    public function getBaseInfo(){
        $appid = $this->appid;
        //微信回调的url
        $redirect_uri = urlencode("https://qq963087326.myue.xzbiz.cn/index.php/Weixin/index/getUerOpenId");
        // scope 参数说明
        // snsapi_base 不需要用户授权就能获取openid
        //以snsapi_userinfo 需要用户同意,获取用户基本信息.比snsapi_base信息多
        //额外参数 state 
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
        header("location:".$url);
    }
    public function getUerOpenId(){
        $appid = $this->appid;
        $secret = $this->secret;
        $code = $_GET['code'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url);
        var_dump($res);exit;
    }
    //和上面getBaseInfo方法一样的,只有scope参数说明参数不一样
    public function getUserDetail(){
        $appid = $this->appid;
        //微信回调的url
        $redirect_uri = urlencode("https://qq963087326.myue.xzbiz.cn/index.php/Weixin/index/getUerOpenId");
        //scope参数说明
        // snsapi_base 不需要用户授权就能获取openid
        //以 snsapi_userinfo 需要用户同意,获取用户基本信息.比snsapi_base信息多
        //额外参数 state 
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        header("location:".$url);
    }
    public function getUserInfo(){
        //获取网页授权的access_token
        $appid = $this->appid;
        $secret = $this->secret;
        $code = $_GET['code'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url);
        $res = json_decode($res,true);
        $access_token = $res['access_token'];
        $openid = $res['openid'];
        //拉取用户的详细信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $getCurl = new \Org\Curl\Curl;
        $res = $getCurl->getCurl($url);
        var_dump($res);exit;  
    }
    //获取JsApiTickte
    public function getJsApiTickte(){
        if($_SESSION['time']>time()&&$_SESSION['tickte']){
            $JsApiTicket = $_SESSION['time'];
        }else{  
            $access_token = $this->getWxAccesstoken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $getCurl = new \Org\Curl\Curl;
            $res = $getCurl->getCurl($url);
            $res = json_decode($res,true);
            $JsApiTicket = $res['ticket'];
            $_SESSION['tickte'] = $ticket;
            $_SESSION['time'] = time()+7200;
        }
        return $JsApiTicket;
    }
    //获取16位随机码(多少位都可以)
    public function getRandCode(){
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        $length = strlen($chars)-1;
        for($i=0;$i<=16;$i++){
            $str.=substr($chars, mt_rand(0,$length),1);
        }
        //var_dump(substr(str_shuffle($chars),0,16)); 
        echo $str;
    }
    public function shareWx(){
        //1.获取jsapi_tickte票据
        $jsapi_tickte = $this->getJsApiTickte();     
        $url = "http://qq963087326.myue.xzbiz.cn/index.php/Weixin/index/shareWx";
        $timestamp = time();
        $noncestr = $this->getRandCode();
        //获取signature
        $signature = "jsapi_ticket=".$jsapi_tickte."&noncestr=".$noncestr."&url=".$url;
        $signature =sha1($signature);

        $this->assign('name',"若水测试");
        $this->assign('timestamp',$timestamp);
        $this->assign('noncestr',$noncestr);
        $this->assign('signature',$signature);
        $this->display('Index/share');
    }
    public function auto_response($content){
        $ch = curl_init();
        $key = "841ecdb1bf28463f9db3f1c77847f0c0";
        $content = $content;
        $url = 'http://www.tuling123.com/openapi/api?key='.$key.'&info='.$content;
        $header = array(
           'apikey: 4d04db77f08896f94d996b7bc5074cab',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);
        // public 'code' => int 100000
        // public 'text' => string '你还有什么不开心的事说出来让窝开心下'
        /*echo "<pre>";
        print_r($res);
        exit;*/
        $ret = json_decode($res);
        return $ret->text;
    }
    public function weather(){
        //测试Vendor函数
        /*$a = Vendor('IndexModel',dirname(__FILE__),'.php');
        $IndexModel = new \IndexModel();*/   
        $ch = curl_init();
       $url = 'http://apis.baidu.com/apistore/weatherservice/weather?cityname=石家庄';
       $header = array(
           'apikey: 4d04db77f08896f94d996b7bc5074cab',
       );
       // 添加apikey到header
       curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       // 执行HTTP请求
       curl_setopt($ch , CURLOPT_URL , $url);
       $res = curl_exec($ch);

       var_dump(json_decode($res));
    }
    public function idCard(){
        $ch = curl_init();
        $url = 'http://apis.baidu.com/apistore/idservice/id?id=130633199310304713';
        $header = array(
            'apikey: 4d04db77f08896f94d996b7bc5074cab',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);

        var_dump(json_decode($res));
    }


}